<?php


namespace app\common\lib\sms;

use app\common\exception\LogicException;
use Qcloud\Sms\SmsSingleSender;
use Qcloud\Sms\SmsMultiSender;
use think\facade\Config;

class TencentSms implements Sms
{

    /**
     * @param $mobile
     * @param $templateCode
     * @param  array  $templateParam
     * @return bool
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/5/8
     * @Time: 17:53
     */
    public static function send($mobile, $templateCode, $templateParam): bool
    {
        // TODO: Implement send() method.
        try {
            $sender = new SmsSingleSender(Config::get('system.tencent_sms.appid'),
                Config::get('system.tencent_sms.appkey'));

            $code   = [random_int(100000, 999999)];
            $result = $sender->sendWithParam('86', $mobile, $templateCode,
                $code, Config::get('system.tencent_sms.sms_sign'), "", "");  // 签名参数不能为空串


            $resultArr = json_decode($result, true);
            if ($resultArr['result'] === 0 && $resultArr['errmsg'] === 'OK') {
                return true;
            }
            throw new LogicException(['msg' => '发送失败！', 'data' => $resultArr]);
        } catch (\Exception $exception) {
            //var_dump($exception->getMessage());die;
            throw $exception;
        }
    }

    /**
     * @param  array  $mobiles
     * @param $templateCode
     * @param  array  $templateParam
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/5/8
     * @Time: 19:18
     */
    public static function multiSend(array $mobiles, $templateCode, $templateParam)
    {
        // TODO: Implement multiSend() method.
        try {
            $multiSend = new SmsMultiSender(Config::get('system.tencent_sms.appid'),
                Config::get('system.tencent_sms.appkey'));
            $code   = [random_int(100000, 999999)];
            $result    = $multiSend->sendWithParam("86", $mobiles,
                $templateCode, $code, Config::get('system.tencent_sms.sms_sign'), "", "");  // 签名参数不能为空串
            $rsp       = json_decode($result);
            echo $result;
        } catch (\Exception $e) {
            echo var_dump($e);
        }
    }
}